package dbinit;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import core.profile.model.BasicProfileAv;
import core.util.HibernateCoreUtil;

public class InitBasicProfileAv {

	public static Long doinit(String name,String value,String datatype ,Long basicprofileId)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		BasicProfileAv basicprofileav = new BasicProfileAv();
		int dataTypeTrue = 0 ;
		if(datatype != null && datatype.trim() != "")
		{
			if(datatype == "string")
			{
				basicprofileav.setStringvalue(value);
				dataTypeTrue = 1 ;
			}
			else if(datatype == "int")
			{
				basicprofileav.setIntvalue(Integer.parseInt(value));
				dataTypeTrue = 1 ;
			}
			else if(datatype == "float")
			{
				basicprofileav.setFloatvalue(Float.parseFloat(value));
				dataTypeTrue = 1 ;
			}
			else if(datatype == "date")
			{
				SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
				java.util.Date jud = null; 
				try {
					jud = formatter.parse(value);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				java.sql.Date jsqlD = new java.sql.Date(jud.getTime());
				basicprofileav.setDatevalue(jsqlD);
				dataTypeTrue = 1 ;
			}
			else
			{
				System.out.println("Datatype could not match");
				return 0L;
			}
		}
		Long uuid = null;
	    if(dataTypeTrue ==1 )
	    {
			basicprofileav.setName(name);
	    	basicprofileav.setDatatype(datatype);
	    	basicprofileav.setBasicprofile(InitBasicProfile.getBasicProfileByUuid(basicprofileId));
	    	try
	    	{
	    		transaction = session.beginTransaction();
	    		uuid = (Long)session.save(basicprofileav);
	    		transaction.commit();
	    	}
	    	catch(HibernateException he)
	    	{
	    		he.printStackTrace();
	    	}
	    }
		return uuid ;
	}
}
